<?php

class HistoryController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/main';

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$model = new SearchForm();
		$criteria = new CDbCriteria();
		
		if (Yii::app()->user->getId()) {
			$criteria->addCondition('user = "' . Yii::app()->user->getId() . '"', 'OR');
		} 
		
		$criteria->addCondition('shared = "1"', 'OR');
		
		if(isset($_POST['SearchForm']))
		{
			$model->attributes=$_POST['SearchForm'];
			
			$criteria->addSearchCondition('body', $model->string, true, 'AND');
			$criteria->addSearchCondition('header', $model->string, true, 'OR');
			$criteria->addSearchCondition('footer', $model->string, true, 'OR');
			$criteria->addSearchCondition('comment', $model->string, true, 'OR');
			$criteria->addSearchCondition('uuid', $model->string, true, 'OR');
		} else {
			$criteria->limit = 25;
		}
				
		$criteria->order = 'timestamp DESC';
		
		$searchResult = History::model()->findAll($criteria);
		
		$this->render('admin',array(
			'model' => $model,
			'searchResult'=>$searchResult,
		));
	}
	
	public function actionShare($id)
	{
		$criteria = new CDbCriteria();
		$criteria->addCondition('user = "' . Yii::app()->user->getId() . '"');
		$criteria->addCondition('uuid = "' . $id . '"');
		
		$history = History::model()->find($criteria);
		$history->shared    = $history->shared == '1' ? '0' : '1';
		$history->save();
		
		if ($history->shared == '0') {
			Yii::app()->user->setFlash('success', Yii::t('controller', 'Template unshared. Other users cannot access the template anymore'));
		} else {
			Yii::app()->user->setFlash('success', Yii::t('controller', 'Template shared with all users'));
		}

		$this->redirect(array('/history'));
	}
}
